package com.sh.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.sh.springbootinit.common.BaseResponse;
import com.sh.springbootinit.common.ErrorCode;
import com.sh.springbootinit.common.ResultUtils;
import com.sh.springbootinit.exception.BusinessException;
import com.sh.springbootinit.manager.OssManager;
import com.sh.springbootinit.model.enums.FileUploadBizEnum;
import com.sh.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Value("${aliyun.oss.filePrefix}")
    private String filePrefix;  // 注入配置中的前缀

    @Resource
    private OssManager ossManager;


    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile file) {
        // 获取文件名
        String fileName = filePrefix + file.getOriginalFilename();
        // 上传文件到 OSS
        String url = ossManager.uploadFileToOSS(file, fileName);
        // 返回文件访问路径
        return ResultUtils.success(url);
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
